package me.sdevil507.mobile.wxApplet.controller;

import com.alibaba.fastjson.JSONObject;
import me.sdevil507.mobile.wxApplet.dto.BwechatCheckUserDTO;
import me.sdevil507.mobile.wxApplet.model.WXSessionModel;
import me.sdevil507.mobile.wxApplet.model.WxBO;
import me.sdevil507.mobile.wxApplet.model.WxOcrBO;
import me.sdevil507.mobile.wxApplet.service.WxCheckUserService;
import me.sdevil507.mobile.wxApplet.service.WxWebService;
import me.sdevil507.mobile.wxApplet.util.HttpClientUtil;
import me.sdevil507.mobile.wxApplet.util.JsonUtils;
import me.sdevil507.mobile.wxApplet.util.WxConstant;
import me.sdevil507.mobile.wxApplet.util.WxUtil;
import me.sdevil507.supports.result.ApiResultDTO;
import me.sdevil507.supports.result.ApiResultGenerator;
import me.sdevil507.supports.status.ApiStatusCode;
import me.sdevil507.supports.util.JwtUtil;
import me.sdevil507.systemAssist.Constant.SystemAssistConstant;
import me.sdevil507.systemAssist.systemLog.annotation.OperLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/wechat")
public class WxLoginController {

	@Autowired
	WxWebService wxWebService;

	@Autowired
	WxCheckUserService wxCheckUserService;

	@Autowired
	RedisTemplate redisTemplate;


	@RequestMapping(value = "/getUserOpenIdInfo",method = RequestMethod.POST)
	public ApiResultDTO getUserOpenIdInfo(@RequestBody WxBO wxBO) {
		Map<String, String> param = new HashMap<>();
		param.put("appid", WxConstant.COLLECT_FRUIT_APPID);
		param.put("secret", WxConstant.COLLECT_FRUIT_APPSECRET);
		param.put("js_code", wxBO.getCode());
		param.put("grant_type", WxConstant.GRANTTYPE);

		WXSessionModel model = this.getOpenIdAndSessionKey(param);

		return ApiResultGenerator.create("0", "获取openId成功!", model);
	}

	/**
	 *	获取openId及sessionKey
	 *
	 * @return
	 */
	private WXSessionModel getOpenIdAndSessionKey(Map<String, String> param){
		WXSessionModel model = null;
		String wxResult = "";
		try {
			wxResult = HttpClientUtil.doGet(WxConstant.SESSION_URL, param);
			System.out.println("微信返回的结果-获取WXSessionModel---" + wxResult);
			model = JsonUtils.jsonToPojo(wxResult, WXSessionModel.class);
		}catch (Exception e){
			System.out.println("微信授权失败-获取session_key失败---" + wxResult);
		}
		return model;
	}

	/**
	 * 微信获取accessToken
	 */
	@RequestMapping(value = "/getWxAccessToken",method = RequestMethod.POST)
	public ApiResultDTO getWxAccessToken() {

		try {
			String accessToken = WxUtil.getAccessToken(WxConstant.COLLECT_FRUIT_APPID, WxConstant.COLLECT_FRUIT_APPSECRET);

			return  ApiResultGenerator.create("0", "accessToken获取成功!", accessToken);

		} catch (Exception e) {
			e.printStackTrace();
			return  ApiResultGenerator.create("-1", "accessToken获取失败!");
		}
	}

	/**
	 * 微信授权登陆  返回用户所属机构信息  来让用户确认
	 * @param wxBO
	 * @return
	 */
	@OperLog(operTerminal = SystemAssistConstant.systemAssistTerminal.WECHAT, operClassify = SystemAssistConstant.systemAssistClassify.SECURITY, operModule = SystemAssistConstant.systemAssistModule.LOGIN, operDesc = "")
	@RequestMapping(value = "/wxManagerFastLogin",method = RequestMethod.POST)
	public ApiResultDTO wxManagerFastLogin(@RequestBody WxBO wxBO) {

		ApiResultDTO apiResultDTO = null;

		try {
			String accessToken = WxUtil.getAccessToken(WxConstant.COLLECT_FRUIT_APPID, WxConstant.COLLECT_FRUIT_APPSECRET);
			String phoneNumber = WxUtil.getPhoneNumber(accessToken, wxBO.getCode());
			//获取token  0: 专家
			apiResultDTO = wxWebService.loginAndGetInfo(phoneNumber, wxBO);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return apiResultDTO;
	}


	/**
	 * 验证token是否过期  true:已过期
	 * @param wxBO
	 * @return
	 */
	@RequestMapping(value = "/verifyToken",method = RequestMethod.POST)
	public ApiResultDTO verifyToken(@RequestBody WxBO wxBO) {

		long key = 0;
		try {
			String phoneNumber = JwtUtil.getPhoneNumber(wxBO.getToken());
			// 如果该值有过期时间，就返回相应的过期时间;
			// 如果该值没有设置过期时间，就返回-1;
			// 如果没有该值，就返回-2;
			key = redisTemplate.opsForValue().getOperations().getExpire(JwtUtil.JWT_SHIRO_CACHE_KEY_PREFIX + phoneNumber);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return ApiResultGenerator.create("0", "验证成功, true代表已过期!", key <= 1);
	}

	/**
	 * 确认信息正确 获取token
	 * @param wxBO
	 * @return
	 */
	@RequestMapping(value = "/getToken",method = RequestMethod.POST)
	public ApiResultDTO getToken(@RequestBody WxBO wxBO) {

		ApiResultDTO apiResultDTO = null;
		try {
			apiResultDTO = wxWebService.getToken(wxBO);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return apiResultDTO;
	}

	/**
	 * 临时专家 输入姓名来比对临时专家及返回成果数据
	 * @param wxBO
	 * @return
	 */
	@RequestMapping(value = "/compareTempExpertInfo",method = RequestMethod.POST)
	public ApiResultDTO compareTempExpertInfo(@RequestBody WxBO wxBO) {

		ApiResultDTO apiResultDTO = null;
		try {
			apiResultDTO = wxWebService.compareTempExpertInfo(wxBO);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return apiResultDTO;
	}

	/**
	 * 添加待审核记录
	 * @return
	 */
	@RequestMapping(value = "/saveWxCheckUserData",method = RequestMethod.POST)
	public ApiResultDTO saveWxCheckUserData(@RequestBody BwechatCheckUserDTO dto) {
		try {
			wxCheckUserService.saveWxCheckUserData(dto.getRealName(), dto.getPhoneNumber(), dto.getOrgId(), dto.getStatus());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ApiResultGenerator.create("0", "请等待智库审核!");
	}


	/**
	 *	ocr识别
	 *
	 */
	@PostMapping("/getWxOcrText")
	private ApiResultDTO getWxOcrText(@RequestBody WxOcrBO wxOcrBO){
		String wxResult = "";
		ApiResultDTO apiResultDto;
		try {
//			Map<String, String> param = new HashMap<>();
////			param.put("access_token", WxUtil.getAccessToken(WxConstant.COLLECT_FRUIT_APPID, WxConstant.COLLECT_FRUIT_APPSECRET));
//			param.put("type", "image");
//			param.put("img_url", wxOcrBO.getImgUrl());

			wxResult = HttpClientUtil.doPost(WxConstant.ORC_URL + "?access_token=" + WxUtil.getAccessToken(WxConstant.COLLECT_FRUIT_APPID, WxConstant.COLLECT_FRUIT_APPSECRET) + "&img_url=" + wxOcrBO.getImgUrl());
			System.out.println("微信返回的结果-获取OCR---" + wxResult);
			apiResultDto = ApiResultGenerator.create(ApiStatusCode.SUCCESS.getCode(), "ocr识别成功!", JSONObject.parse(wxResult));
		}catch (Exception e){
			System.out.println("微信授权失败-获取OCR失败---" + wxResult);
			apiResultDto = ApiResultGenerator.create(ApiStatusCode.SUCCESS.getCode(), "获取OCR失败!");
		}
		return apiResultDto;
	}
}
